package com.lin;

/**
 * @Author zimingl
 * @Date 2023/4/30 9:57
 * @Description: TODO
 */
public class CASCounter {
    private volatile int count;

    public int getCount() {
        return count;
    }

    public void increment() {
        int oldValue, newValue;
        do {
            oldValue = count;
            newValue = oldValue + 1;
        } while (!compareAndSwap(oldValue, newValue));
    }

    private synchronized boolean compareAndSwap(int oldValue, int newValue) {
        if (count == oldValue) {
            count = newValue;
            return true;
        }
        return false;
    }
}
